package com.lyz.myself.controller.login;

import com.github.pagehelper.PageInfo;
import com.lyz.myself.config.exception.CustomUnauthorizedException;
import com.lyz.myself.config.utils.JedisUtil;
import com.lyz.myself.config.utils.JwtUtil;
import com.lyz.myself.config.utils.Result;
import com.lyz.myself.config.utils.base.CodeMsg;
import com.lyz.myself.config.utils.util.DateUtil;
import com.lyz.myself.config.utils.util.StringUtil;
import com.lyz.myself.config.utils.util.WebUtil;
import com.lyz.myself.controller.BaseController;
import com.lyz.myself.pojo.Po.Position;
import com.lyz.myself.pojo.Po.Role;
import com.lyz.myself.pojo.Po.User;
import com.lyz.myself.pojo.Po.common.Constant;
import com.lyz.myself.pojo.Vo.UserLoginVo;
import com.lyz.myself.service.PositionService;
import com.lyz.myself.service.RoleService;
import com.lyz.myself.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.lyz.myself.config.utils.util.MD5Util.commonMD5;

@Api(description = "用户模块")
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @Autowired
    private PositionService positionService;

    @Autowired
    private RoleService roleService;

    /**
     * RefreshToken过期时间
     */
    @Value("${refreshTokenExpireTime}")
    private String refreshTokenExpireTime;


    @RequestMapping(value = "/getMessage", method = RequestMethod.GET)
    public Result getMessage() {
        return Result.success("您拥有用户权限，可以获得该接口的信息！");
    }

    @ApiOperation("查询所有用户的姓名手机号")
    @RequiresAuthentication
    @RequestMapping(value = "/getAllUser", method = RequestMethod.GET)
    public Result getAllUser(Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageSize == null) {
            pageNum = 1;
            pageSize = 10;
        }
        int company_id = getUser().getCompany_id();
        PageInfo<Map<String, String>> pageInfo = userService.getAllUser(company_id, pageNum, pageSize);
        if (pageInfo.getSize() > 0) {
            return Result.success(pageInfo, "查询成功！");
        } else {
            return Result.error(CodeMsg.ERROR, "暂无信息！");
        }
    }

    @ApiOperation("查看个人信息")
    @RequiresAuthentication
    @RequestMapping(value = "/fidMeInformation", method = RequestMethod.GET)
    public Result fidMeInformation() {
        Integer user_id = JwtUtil.getUserId();
        int company_id = getUser().getCompany_id();
        Map<String, String> fidMeInformation = userService.fidMeInformation(user_id, company_id);
        if (fidMeInformation != null) {
            return Result.success(fidMeInformation, "个人信息查询成功！");
        } else {
            return Result.error(CodeMsg.ERROR, "暂无个人信息！");
        }
    }

    @ApiOperation("用户注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Result register(@RequestBody User user) {
        if(user.getImg()==null){
            user.setImg("");
        }
        if(user.getSex()==null){
            user.setSex(0);
        }
        if(user.getEmail()==null){
            user.setEmail("");
        }
        if(user.getTelephone()==null){
            user.setTelephone("");
        }
        if(user.getAddress()==null){
            user.setAddress("");
        }
        if(user.getNavigation()==null){
            user.setNavigation("");
        }
        if(user.getSimple_menu()==null){
            user.setSimple_menu("");
        }
        if(user.getDashboard()==null){
            user.setDashboard("");
        }
        if(user.getWeixinid()==null){
            user.setWeixinid("");
        }
        if (StringUtil.isEmpty(user.getName())) {
            return Result.error(CodeMsg.ERROR, "用户名不能为空！");
        }
        User u = userService.getUser(user.getName());
        if (null != u) {
            return Result.error(CodeMsg.ERROR, "用户名已被占用！");
        }
        if (user.getPassword().length() < 6) {
            return Result.error(CodeMsg.ERROR, "密码不能小于6位！");
        }
        String salt = String.valueOf(ByteSource.Util.bytes(user.getName()));
        salt = salt.substring(0, 4);
        String password = commonMD5(commonMD5(user.getPassword()) + salt);
        user.setSalt(salt);
        user.setReg_time(DateUtil.timeMillis());
        user.setPassword(password);
        user.setStatus(1);
        if (null == user.getRole_id()) {
            user.setRole_id(0);
        }
        if (null == user.getCompany_id()) {
            user.setCompany_id(0);
        }
        if (null == user.getCategory_id()) {
            user.setCategory_id(2);
        }
        user.setLast_login_time(0);
        user.setReg_time(0);
        user.setLast_read_time("");
        user.setLostpw_time(DateUtil.timeMillis());
        user.setReg_ip(WebUtil.getInstance().getIpAddress());
        Integer i = userService.insertSelective(user);
        if (i > 0) {
            return Result.success("注册成功！");
        } else {
            return Result.error(CodeMsg.ERROR, "注册失败！");
        }
    }

    @ApiOperation("绑定用户")
    @RequestMapping(value = "/bindTheUser", method = RequestMethod.POST)
    public Result bindTheUser(String userName, String password, String vaderName, Integer compamy_id) {
        if(vaderName!=null&&userName!=null&&password!=null&&compamy_id!=null){


        User users = userService.findTheUser(vaderName);
        if(users==null){
        User user = userService.getUserByCompany(userName, compamy_id);
        if (user == null) {
            throw new CustomUnauthorizedException("该帐号不存在");
        }
        String key = commonMD5(commonMD5(password) + user.getSalt());
        if (key.equals(user.getPassword())) {
            Map<String, Object> map = new HashMap();
            map.put("binding_vader", vaderName);
            map.put("user_id", user.getUser_id());
            int insertVeida = userService.bindTheUser(map);
            if (insertVeida > 0) {
                return Result.success(insertVeida, "绑定成功！");
            } else {
                return Result.error(CodeMsg.ERROR, "绑定失败");
            }

        } else {
            throw new CustomUnauthorizedException("帐号或密码错误");
        }
    }else{
            return Result.error(CodeMsg.ERROR, "该账号已绑定");
    }
        }else{
            return Result.error(CodeMsg.ERROR, "账号或密码或公司id或维达账号未输入");
        }
    }

    @ApiOperation("通过绑定维达的账号登陆")
    @RequestMapping(value = "/findTheUser", method = RequestMethod.POST)
    public Result findTheUser(String vdaderId, HttpServletResponse httpServletResponse) {
        if (vdaderId != null) {
            User user = userService.findTheUser(vdaderId);
            if (user != null) {
                UserLoginVo userVo = ejbGenerator.convert(user, UserLoginVo.class);
                String userType =  positionService.getDescription(user.getUser_id());
                if(userType!=null){
                    if(userType.equals("admin")){
                        userVo.setUserType("超级管理员");
                    }else if(userType.equals("CEO")){
                        userVo.setUserType("CEO");
                    }else if(userType.equals("companyAdmin")){
                        userVo.setUserType("机构管理员");
                    }else{
                        System.out.println("");
                        userVo.setUserType("普通员工");
                    }
                }else{
                    userVo.setUserType("游客");
                }
                // 清除可能存在的Shiro权限信息缓存
                if (JedisUtil.exists(Constant.PREFIX_SHIRO_CACHE + user.getUser_id())) {
                    JedisUtil.delKey(Constant.PREFIX_SHIRO_CACHE + user.getUser_id());
                }
                // 设置RefreshToken，时间戳为当前时间戳，直接设置即可(不用先删后设，会覆盖已有的RefreshToken)
                String currentTimeMillis = String.valueOf(System.currentTimeMillis());
                JedisUtil.setObject(Constant.PREFIX_SHIRO_REFRESH_TOKEN + user.getUser_id() + "", currentTimeMillis, Integer.parseInt(refreshTokenExpireTime));
                // 从Header中Authorization返回AccessToken，时间戳为当前时间戳
                String token = JwtUtil.sign(user.getUser_id() + "", currentTimeMillis);
                httpServletResponse.setHeader("Authorization", token);
                httpServletResponse.setHeader("Access-Control-Expose-Headers", "Authorization");
                return Result.success(userVo, "登录成功！");
            } else {
                return Result.error(CodeMsg.ERROR, "该账号未绑定");
            }
        } else {
            return Result.error(CodeMsg.ERROR, "请输入维达账号id");
        }
    }

    @ApiOperation("增加机构管理员(只有admin权限的用户才可以添加)")
    @RequiresAuthentication//登陆状态
    @RequiresRoles(value = {"admin"}, logical = Logical.OR)
    @RequestMapping(value = "/insertAdministrator", method = RequestMethod.POST)
    public Result insertAdministrator(@RequestBody User user) {
        if (StringUtil.isEmpty(user.getName())) {
            return Result.error(CodeMsg.ERROR, "用户名不能为空！");
        }
        User u = userService.getUser(user.getName());
        if (null != u) {
            return Result.error(CodeMsg.ERROR, "用户名已被占用！");
        }
        if (user.getPassword().length() < 6) {
            return Result.error(CodeMsg.ERROR, "密码不能小于6位！");
        }
        String salt = String.valueOf(ByteSource.Util.bytes(user.getName()));
        salt = salt.substring(0, 4);
        String password = commonMD5(commonMD5(user.getPassword()) + salt);
        user.setSalt(salt);
        user.setReg_time(DateUtil.timeMillis());
        user.setPassword(password);
        user.setStatus(1);
        List<Position> list = positionService.positionList(user.getCompany_id());
        if (null == user.getRole_id()) {
            user.setRole_id(0);
        }
        if (null == user.getCompany_id()) {
            user.setCompany_id(0);
        }
        if (null == user.getCategory_id()) {
            user.setCategory_id(2);
        }
        user.setLast_login_time(0);
        user.setReg_time(0);
        user.setLast_read_time("");
        user.setLostpw_time(DateUtil.timeMillis());
        user.setReg_ip(WebUtil.getInstance().getIpAddress());
        Integer i = userService.insertSelective(user);
        Map<String, Object> map = new HashMap<>();
        Role role = roleService.getRole((Integer) map.get("position_id"), user.getCompany_id());
        for (int j = 0; j < list.size(); j++) {
            if (list.get(j).getName().equals("companyAdmin") && list.get(j).getCompany_id() == 0) {
                map.put("position_id", list.get(j).getPosition_id());
            }
        }
        Role ro = new Role();
        ro.setCompany_id(user.getCompany_id());
        ro.setPosition_id((Integer) map.get("position_id"));
        ro.setUser_id(user.getUser_id());
        int insertRole = roleService.insert(ro);
        User us = new User();
        us.setRole_id(ro.getRole_id());
        us.setUser_id(user.getUser_id());
        int updateRoleid = userService.updateByPrimaryKeySelective(us);
        if (i > 0 && insertRole > 0 && updateRoleid > 0) {
            return Result.success("注册机构管理员成功！");
        } else {
            return Result.error(CodeMsg.ERROR, "注册机构管理员失败！");
        }
    }

    @ApiOperation("删除机构管理员(只有admin权限的用户才可以删除)")
    @RequiresAuthentication//登陆状态
    @RequiresRoles(value = {"admin"}, logical = Logical.OR)
    @RequestMapping(value = "/deleteAdmin", method = RequestMethod.POST)
    public Result deleteAdmin(String user_id) {
        if (user_id != null) {
            List<Integer> list = new ArrayList<Integer>();
            String[] str = user_id.split(",");
            for (int i = 0; i < str.length; i++) {
                list.add(Integer.parseInt(str[i]));
            }
            boolean delete = userService.deleteAdmin(list);
            if (delete==true) {
                return Result.success("删除用户成功！");
            } else {
                return Result.error(CodeMsg.ERROR, "删除用户失败！");
            }
        } else {
            return Result.error(CodeMsg.ERROR, "请选择要删除的用户！");
        }
    }

    @ApiOperation("修改机构管理员(只有admin权限的用户才可以修改)")
    @RequiresAuthentication//登陆状态
    @RequiresRoles(value = {"admin"}, logical = Logical.OR)
    @RequestMapping(value = "/updateAdmin", method = RequestMethod.POST)
    public Result updateAdmin(@RequestBody User user) {
        if (user != null) {
            if (user.getPassword() != null) {
                String salt = String.valueOf(ByteSource.Util.bytes(user.getName()));
                salt = salt.substring(0, 4);
                String password = commonMD5(commonMD5(user.getPassword()) + salt);
                user.setSalt(salt);
                user.setPassword(password);
                user.setLostpw_time(DateUtil.timeMillis());
            }
            int updateAdm = userService.updateByPrimaryKeySelective(user);
            if (updateAdm > 0) {
                return Result.success("用户信息修改成功！");
            } else {
                return Result.error(CodeMsg.ERROR, "用户信息修改失败！");
            }
        } else {
            return Result.error(CodeMsg.ERROR, "请输入要修改的用户信息！");
        }
    }


    @ApiOperation("解绑维达账号")
    @RequiresAuthentication//登陆状态
    @RequestMapping(value = "/unbundlingUser", method = RequestMethod.POST)
    public Result unbundlingUser() {
          String user = userService.unbundlingUser(getUser().getUser_id());
          if(user!=null){
              User users = new User();
              users.setBinding_vader("");
              users.setUser_id(getUser().getUser_id());
             int upUser = userService. updateByPrimaryKeySelective(users);
              if (upUser > 0) {
                  return Result.success("解绑成功！");
              } else {
                  return Result.error(CodeMsg.ERROR, "解绑失败！");
              }
          }else{
              return Result.error(CodeMsg.ERROR, "该账户未绑定！");
          }
    }


}

